package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.config.BlogException;
import com.example.mapper.BlogInfoMapper;
import com.example.mapper.UserInfoMapper;
import com.example.model.BlogInfo;
import com.example.model.UserInfo;
import com.example.model.UserInfoResponse;
import com.example.model.UserLoginResponse;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import com.example.utils.MD5Util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-08-03
 * Time: 20:32
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private BlogInfoMapper blogInfoMapper;
    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    @Override
    public UserLoginResponse login(String userName, String password) {
        //1.查询数据库，根据用户名查询用户信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().
                eq(UserInfo::getUserName, userName).eq(UserInfo::getDeleteFlag,0)
        );

        //2.验证账号密码是否正确
        if(userInfo == null || userInfo.getId() == null){
            throw new BlogException("用户不存在");
        }
        //使用MD5加盐验证密码
        if(!MD5Util.verify(password,userInfo.getPassword())){
            throw new BlogException("用户密码输入错误");
        }
        //3.账号密码正确，生成token
        //设置JWT令牌第二部分内容
        Map<String,Object> claim = new HashMap<>();
        claim.put("userId",userInfo.getId());
        claim.put("userName",userInfo.getUserName());
        //生成JWT令牌
        String token = JwtUtils.genJwt(claim);
        return new UserLoginResponse(userInfo.getId(),token);

    }

    /**
     * 注册
     * @param userName
     * @param password
     * @return
     */
    @Override
    public Boolean register(String userName, String password, String githubUrl) {
        // 1. 检查用户名是否已存在
        UserInfo existingUser = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName));

        if (existingUser != null) {
            throw new BlogException("用户名已存在");
        }

        // 2. 创建新用户
        UserInfo newUser = new UserInfo();
        newUser.setUserName(userName);
        // 使用MD5加盐加密密码
        newUser.setPassword(MD5Util.encrypt(password));
        newUser.setGithubUrl(githubUrl);
        newUser.setCreateTime(new Date());
        newUser.setUpdateTime(new Date());
        newUser.setDeleteFlag(0);

        // 3. 保存到数据库
        int result = userInfoMapper.insert(newUser);

        //4.返回注册结果
        return result > 0;
    }

    /**
     * 博客列表页，获取用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        //1.查询数据库，根据用户id查询用户信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().
                eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag,0)
                );
        //2.将查询结果转换成响应对象
        //因为用了selectOne，所以查询结果是一个对象，而不是一个集合，所以不能用 stream
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        BeanUtils.copyProperties(userInfo,userInfoResponse);
        return userInfoResponse;
    }


    /**
     * 博客详情页，获取用户信息
     * @param blogId
     * @return
     */
    @Override
    public UserInfoResponse getAuthorInfoByBlogId(Integer blogId) {
        //1.查询数据库，根据博客id查询博客表的用户信息
        BlogInfo blogInfo = blogInfoMapper.selectOne(new LambdaQueryWrapper<BlogInfo>().
                eq(BlogInfo::getId, blogId).eq(BlogInfo::getDeleteFlag,0)
                );
        //2.根据用户信息中的作者id，查询对应作者表的作者信息
        if(blogInfo == null){
            throw new BlogException("博客不存在");
        }
        UserInfo authorInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().
                eq(UserInfo::getId, blogInfo.getUserId()).eq(UserInfo::getDeleteFlag,0)
                );
        //3.将查询结果转换成响应对象
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        BeanUtils.copyProperties(authorInfo,userInfoResponse);
        return userInfoResponse;
    }

}
